const logger = require('./builder.log');
const shell = require('./builder.shell');
const helper = require('./builder.helper');

const ManifestBuilder = function(){

    let _build = function *(distPath, appConfig, appPages) {

        //生成 app.js
        result = yield shell.exec(`cp src/app.js  ${distPath}/`);
        if(result === false){
            logger.error("生成 app.js失败");
            return;
        }

        //复制 app.css
        let appCss = yield shell.exec(`cat src/app.css`);
        yield shell.exec(`echo '${appCss}' > ${distPath}/app.wxss`);
        /*result = yield shell.exec(`cp src/app.css  ${distPath}/`);
        if(result === false){
            logger.error("复制 app.css失败");
            return;
        }*/

        //复制公共目录
        result = yield shell.exec(`cp -r src/common/*  ${distPath}/`);
        if(result === false){
            logger.error("复制 common文件失败");
            return;
        }

        //生成 app.json
        let manifest = {};
        let pages = [];
        let tabBar = appConfig.tabBarConfigs;
        let tabBarPages = [];
        for(let i = 0; i < tabBar.list.length; i++ ){
            let x = tabBar.list[i];
            x.pagePath = `pages/page${x.pageId}`;
            if (pages.indexOf(x.pagePath) == -1) {
                pages.push(x.pagePath);
                tabBarPages.push(x.pagePath);
            }
            let iconPath = yield helper.downloadImage(distPath, x.iconPath);
            console.log(iconPath);
            iconPath ? x.iconPath = iconPath : delete x.iconPath;

            let selectedIconPath = yield helper.downloadImage(distPath, x.selectedIconPath);
            console.log(selectedIconPath);
            selectedIconPath? x.selectedIconPath = selectedIconPath : delete x.selectedIconPath;
        }

        appPages.forEach(function (p) {
            let pagePath = `pages/page${p.id}`;
            if (pages.indexOf(pagePath) == -1) {
                pages.push(pagePath);
            }
        });

        //生成 appConfig.js
        let appConfigContent = yield shell.exec(`cat src/appConfig.js`);
        appConfigContent = appConfigContent.replace('{APPKEY}',`${appConfig.appKey}`)
            .replace('{APPSECRET}',`${appConfig.appSecret}`).replace('{TABBARPAGES}',`${JSON.stringify(tabBarPages)}`)
            .replace(/'/g,`"'"`);
        yield shell.exec(`echo '${appConfigContent}' > ${distPath}/appConfig.js`);

        manifest.pages = pages;
        manifest.window = appConfig.windowConfigs;
        manifest.tabBar = tabBar;

        yield shell.exec(`echo '${JSON.stringify(manifest)}' > ${distPath}/app.json`);

        return true;
    };

    return {
        build: _build
    }
}();

module.exports = ManifestBuilder;
